<?php
	if(!isset($_SESSION)){
		session_start();
	}
	// Clear previous messages.
	
	if(isset($_SESSION['error'])) session_unregister('error');
	if(isset($_SESSION['success'])) session_unregister('success');
	$userName = $_SESSION['userName'];

	include("../dbconnection.php");
	
	$i=0;	
	$totalprice = $_POST['totalprice'];
	$date=date("Y-m-d");
	$num = $_SESSION['num'] ;
	$flag=0;
	while ($i <  $num) {
		$itemCode = $_POST['itemcode'.$i];
		if($itemCode!=''){
			if($flag == 0){
				if(mysql_query("INSERT INTO orders (orderDate, userName, totalPrice) VALUES ('$date','$userName','$totalprice')")){
					$_SESSION['success'] = "order added successfully.";
					$flag=1;
				}else{
					$_SESSION['error'] = "Error occured!";
				}
			}
			if($row = mysql_fetch_array(mysql_query("SELECT orderId FROM orders ORDER BY orderId DESC LIMIT 1"))){
				$orderId = $row['orderId'];
				$batchdate = $_POST['batchdate'.$i];
				$quantity = $_POST['quantity'.$i];
				$unitprice = $_POST['unitprice'.$i];
				$amount = $unitprice*$quantity;
				
				if($row2 = mysql_fetch_array(mysql_query("SELECT batchId FROM batches WHERE batches.batchDate = '$batchdate'"))){
					$batchId=$row2['batchId'];
					if(mysql_query("INSERT INTO order_items (orderId, itemCode, batchId, quantity, price) VALUES ($orderId, '$itemCode', $batchId, $quantity, $amount)")){
						if($row = mysql_fetch_array(mysql_query("SELECT stock.stockQuantity FROM stock WHERE stock.itemCode = '$itemCode' AND stock.batchId = $batchId"))){
							$Quantity = $row['stockQuantity'];
							$newQuantity = $Quantity - $quantity;
							echo $newQuantity;
							if(mysql_query("UPDATE stock SET stockQuantity = $newQuantity WHERE stock.itemCode = '$itemCode' AND stock.batchId = $batchId")){
							
							}else{
								$_SESSION['error'] = "Error occured!";
							}					
						}else{
							$_SESSION['error']="Error occured!";
						}
					}else{
						$_SESSION['error'] = "Error occured!";
					}		
				}else{
					$_SESSION['error'] = "Error occured!";
				}	
		
			}else{
				$_SESSION['error'] = "Error occured!";
			}
		}
		$i++;
	}
	if($flag == 0){
		$_SESSION['error'] = "No items to sell";
	}
	
	$_SESSION['page'] = "home.php";
	header('Location: ../../');
	
?>
